<!-- 通用统计图表组件 -->
<template>
  <div class="statistics-container">
    <div class="search-container">
      <div class="date-range">
        <el-date-picker
          v-model="dateRange"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="['00:00:00', '23:59:59']"
          value-format="yyyy-MM-dd"
          @change="handleDateChange"
        ></el-date-picker>
        <el-button type="primary" @click="loadData">查询</el-button>
        <el-button type="info" @click="resetCurrentLevel">重置层级</el-button>
      </div>

      <div class="status-legend">
        <div class="legend-items">
          <div 
            v-for="(status, index) in statusColors" 
            :key="index" 
            class="legend-item"
          >
            <div class="color-box" :style="{ backgroundColor: status.color }"></div>
            <span>{{ status.name }}</span>
          </div>
        </div>
      </div>

      <div class="level-indicator">
        <span>当前层级: </span>
        <el-breadcrumb separator="/">
          <el-breadcrumb-item 
            v-for="(path, index) in navigationPath"
            :key="index"
            :class="{ clickable: index < navigationPath.length - 1 }"
            @click.native="backToLevel(index)"
          >
            {{ path.name }}
          </el-breadcrumb-item>
        </el-breadcrumb>
      </div>
    </div>

    <div class="charts-container">
      <div class="chart-wrapper">
        <echarts-card
          :title="countChartTitle"
          :options="countChartOptions"
          height="100%"
          ref="countChart"
          @chart-click="handleChartClick"
        ></echarts-card>
      </div>
      <div class="chart-wrapper">
        <echarts-card
          :title="areaChartTitle"
          :options="areaChartOptions"
          height="100%"
          ref="areaChart"
          @chart-click="handleChartClick"
        ></echarts-card>
      </div>
    </div>
  </div>
</template>

<script>
import request from '@/utils/request'
import moment from 'moment'
import EchartsCard from '@/components/EchartsCard.vue'

export default {
  name: 'StatisticsChart',
  components: {
    EchartsCard
  },
  props: {
    // API路径
    apiPath: {
      type: String,
      required: true
    },
    // 状态颜色配置
    statusColors: {
      type: Array,
      required: true
    },
    // 数量图表标题
    countChartTitle: {
      type: String,
      default: '需求数量统计'
    },
    // 面积图表标题
    areaChartTitle: {
      type: String,
      default: '需求面积统计(亩)'
    },
    // 状态字段映射 - 将状态映射到返回数据中的字段名
    statusFields: {
      type: Object,
      required: true
    }
  },
  data() {
    return {
      dateRange: [moment().startOf('year').format('YYYY-MM-DD'), moment().format('YYYY-MM-DD')],
      countChartOptions: {},
      areaChartOptions: {},
      currentLevel: 0,  // 当前显示的层级: 0-总部, 1-烟站, 2-乡镇, 3-乡村组
      currentDeptId: null, // 当前选中的部门ID
      navigationPath: [{ id: null, name: '总部', level: 0 }], // 导航路径
      isLoading: false, // 是否正在加载数据
      
      // 完整的树形结构数据（一次性加载，后续不再请求）
      treeData: {
        headOffice: null, // 总部数据
        stations: [], // 烟站数据
        townships: {}, // 乡镇数据，键为烟站ID，值为乡镇数组
        villageGroups: {} // 乡村组数据，键为乡镇ID，值为乡村组数组
      },
      
      // 当前视图的数据（根据当前层级变化）
      viewData: []
    }
  },
  mounted() {
    this.initializeData()
    
    // 为EchartsCard组件添加点击事件
    this.$nextTick(() => {
      if (this.$refs.countChart && this.$refs.countChart.chart) {
        this.$refs.countChart.chart.on('click', this.handleChartClick)
      }
      if (this.$refs.areaChart && this.$refs.areaChart.chart) {
        this.$refs.areaChart.chart.on('click', this.handleChartClick)
      }
    })
  },
  methods: {
    // 初始化数据
    async initializeData() {
      this.isLoading = true
      try {
        // 1. 加载总部数据
        const headOfficeResp = await this.fetchDeptData(0)
        if (headOfficeResp && headOfficeResp.length > 0) {
          // 存储总部数据
          this.treeData.headOffice = headOfficeResp[0]
          
          // 2. 加载烟站数据
          const stationsResp = await this.fetchDeptData(1, this.treeData.headOffice.deptId)
          this.treeData.stations = stationsResp || []
          
          // 3. 为每个烟站加载乡镇数据
          for (const station of this.treeData.stations) {
            const townshipsResp = await this.fetchDeptData(2, station.deptId)
            this.treeData.townships[station.deptId] = townshipsResp || []
          }
          
          // 4. 设置初始视图数据为总部
          this.updateViewForLevel(0)
        }
      } catch (error) {
        console.error('加载数据失败:', error)
        this.$message.error('加载数据失败')
      } finally {
        this.isLoading = false
      }
    },
    
    // 根据部门类型和ID获取数据
    async fetchDeptData(deptType, parentDeptId = null) {
      const params = {
        deptType: deptType,
        startDate: this.dateRange[0],
        endDate: this.dateRange[1]
      }
      
      if (parentDeptId !== null) {
        params.deptId = parentDeptId
      }
      
      const response = await request.get(this.apiPath, { params })
      return response || []
    },
    
    // 加载乡村组数据（按需加载）
    async loadVillageGroupData(townshipId) {
      try {
        // 如果已经加载过，直接使用缓存数据
        if (this.treeData.villageGroups[townshipId]) {
          return this.treeData.villageGroups[townshipId]
        }
        
        // 否则从服务器加载
        const params = {
          deptType: 3, // 乡村组级别
          deptId: townshipId,
          startDate: this.dateRange[0],
          endDate: this.dateRange[1]
        }
        
        const response = await request.get(this.apiPath, { params })
        this.treeData.villageGroups[townshipId] = response || []
        
        return this.treeData.villageGroups[townshipId]
      } catch (error) {
        console.error('加载乡村组数据失败:', error)
        this.$message.error('加载乡村组数据失败')
        return []
      }
    },
    
    // 根据层级设置当前视图
    async updateViewForLevel(level, deptId = null) {
      // 更新当前层级和部门ID
      this.currentLevel = level
      this.currentDeptId = deptId
      
      switch (level) {
        case 0: // 总部层级 - 显示总部和烟站
          this.viewData = this.treeData.stations
          break
          
        case 1: { // 烟站层级 - 显示选中的烟站及其下的乡镇
          if (deptId && this.treeData.townships[deptId]) {
            this.viewData = this.treeData.townships[deptId]
          } else {
            this.viewData = []
          }
          break
        }
          
        case 2: { // 乡镇层级 - 显示选中的乡镇及其下的乡村组
          if (deptId) {
            // 按需加载乡村组数据
            this.viewData = await this.loadVillageGroupData(deptId)
          } else {
            this.viewData = []
          }
          break
        }
          
        default:
          this.viewData = []
      }
      
      // 更新图表
      this.updateCharts()
    },
    
    // 更新图表
    updateCharts() {
      if (!this.viewData || this.viewData.length === 0) {
        // 如果视图数据为空，显示空图表
        const emptyData = this.createEmptyChartData()
        this.countChartOptions = this.createSunburstOptions(emptyData)
        this.areaChartOptions = this.createSunburstOptions(emptyData)
        return
      }
      
      // 构建数量图表数据
      const countData = this.buildChartData('count')
      // 构建面积图表数据
      const areaData = this.buildChartData('area')
      
      // 更新图表选项
      this.countChartOptions = this.createSunburstOptions(countData)
      this.areaChartOptions = this.createSunburstOptions(areaData)
    },
    
    // 构建空图表数据
    createEmptyChartData() {
      const name = this.navigationPath[this.navigationPath.length - 1].name
      return {
        name: name,
        value: 0,
        children: []
      }
    },
    
    // 根据类型构建图表数据
    buildChartData(type) {
      // 获取当前导航路径的最后一项作为中心节点
      const centerNode = this.navigationPath[this.navigationPath.length - 1]
      
      // 创建中心节点
      let rootData = {
        name: centerNode.name,
        value: 0,
        children: []
      }
      
      // 根据当前层级来构建不同的图表数据
      switch (this.currentLevel) {
        case 0: // 总部层级
          if (this.treeData.headOffice) {
            // 使用总部数据作为根节点
            rootData = {
              name: this.treeData.headOffice.deptName,
              value: type === 'count' ? this.treeData.headOffice.totalCount : this.treeData.headOffice.totalArea,
              deptId: this.treeData.headOffice.deptId,
              deptType: this.treeData.headOffice.deptType,
              tooltip: {
                formatter: this.createTooltipFormatter(this.treeData.headOffice, type)
              },
              children: []
            }
          }
          break
          
        case 1: { // 烟站层级
          // 找到当前烟站
          const currentStation = this.treeData.stations.find(s => s.deptId === this.currentDeptId)
          if (currentStation) {
            rootData = {
              name: currentStation.deptName,
              value: type === 'count' ? currentStation.totalCount : currentStation.totalArea,
              deptId: currentStation.deptId,
              deptType: currentStation.deptType,
              tooltip: {
                formatter: this.createTooltipFormatter(currentStation, type)
              },
              children: []
            }
          }
          break
        }
          
        case 2: { // 乡镇层级
          // 找到当前乡镇
          for (const stationId in this.treeData.townships) {
            const township = this.treeData.townships[stationId].find(t => t.deptId === this.currentDeptId)
            if (township) {
              rootData = {
                name: township.deptName,
                value: type === 'count' ? township.totalCount : township.totalArea, 
                deptId: township.deptId,
                deptType: township.deptType,
                tooltip: {
                  formatter: this.createTooltipFormatter(township, type)
                },
                children: []
              }
              break
            }
          }
          break
        }
      }
      
      // 添加子节点
      this.viewData.forEach(dept => {
        const value = type === 'count' ? dept.totalCount : dept.totalArea
        
        if (value > 0) {
          // 创建部门节点
          const deptNode = {
            name: dept.deptName,
            value: value,
            deptId: dept.deptId,
            deptType: dept.deptType,
            itemStyle: { color: this.getColorByType(dept.deptType, 0) },
            tooltip: {
              formatter: this.createTooltipFormatter(dept, type)
            },
            children: []
          }
          
          // 添加状态子节点
          if (type === 'count') {
            this.addStatusNodes(deptNode, dept, 'count')
          } else {
            this.addStatusNodes(deptNode, dept, 'area')
          }
          
          // 添加到根节点
          rootData.children.push(deptNode)
        }
      })
      
      return rootData
    },

    // 添加状态节点
    addStatusNodes(deptNode, dept, type) {
      // 遍历状态字段配置，添加对应的子节点
      this.statusColors.forEach((status) => {
        const fieldName = type === 'count' 
          ? this.statusFields[status.key].count 
          : this.statusFields[status.key].area
        
        const value = dept[fieldName] || 0
        
        if (value > 0) {
          deptNode.children.push({
            name: status.name,
            value: value,
            itemStyle: { color: status.color }
          })
        }
      })
    },
    
    // 创建提示框内容
    createTooltipFormatter(dept, type) {
      return () => {
        let html = `
          <div style="padding: 5px;">
            <div style="font-weight: bold; margin-bottom: 5px;">${dept.deptName}</div>
            <div>${type === 'count' ? '总需求数量' : '总需求面积'}: ${type === 'count' ? dept.totalCount : dept.totalArea}${type === 'area' ? '亩' : ''}</div>
        `
        
        // 添加各状态的数据
        this.statusColors.forEach(status => {
          const fieldName = type === 'count' 
            ? this.statusFields[status.key].count 
            : this.statusFields[status.key].area
          
          const value = dept[fieldName] || 0
          const percentage = dept[`total${type.charAt(0).toUpperCase() + type.slice(1)}`] > 0 
            ? (value / dept[`total${type.charAt(0).toUpperCase() + type.slice(1)}`] * 100).toFixed(1) 
            : 0
          
          html += `<div>${status.name}: ${value}${type === 'area' ? '亩' : ''} (${percentage}%)</div>`
        })
        
        html += '</div>'
        return html
      }
    },
    
    // 获取颜色方案
    getColorByType(deptType, index) {
      // 定义不同层级的颜色方案 - 中等饱和度、柔和配色
      const colorSchemes = {
        // 总部层级颜色 - 中饱和度蓝色系
        0: ['#5d9cbc', '#6ba8c7', '#79b4d2', '#87c0dd', '#95cce8', '#a3d8f3'],
        // 烟站层级颜色 - 中饱和度棕色系
        1: ['#c29a82', '#cda892', '#d8b6a2', '#e3c4b2', '#eed2c2', '#f9e0d2'],
        // 乡镇层级颜色 - 中饱和度绿色系
        2: ['#7db269', '#8bbd79', '#99c889', '#a7d399', '#b5dea9', '#c3e9b9'],
        // 乡村组层级颜色 - 中饱和度紫色系
        3: ['#a587b7', '#b297c4', '#bfa7d1', '#ccb7de', '#d9c7eb', '#e6d7f8']
      }
      
      // 获取当前层级的颜色方案，如果不存在则使用默认颜色方案
      const scheme = colorSchemes[deptType] || [
        '#5d9cbc', '#6ba8c7', '#79b4d2', '#87c0dd',
        '#c29a82', '#cda892', '#d8b6a2', '#e3c4b2',
        '#7db269', '#8bbd79', '#99c889', '#a7d399', 
        '#a587b7', '#b297c4', '#bfa7d1', '#ccb7de'
      ]
      
      // 根据索引获取颜色，如果索引超出范围则循环使用
      return scheme[index % scheme.length]
    },
    
    // 获取整体配色主题
    getColorTheme() {
      return [
        // 基础主题颜色 - 中等饱和度配色
        '#5d9cbc', '#6ba8c7', '#79b4d2', '#87c0dd',
        '#c29a82', '#cda892', '#d8b6a2', '#e3c4b2',
        '#7db269', '#8bbd79', '#99c889', '#a7d399', 
        '#a587b7', '#b297c4', '#bfa7d1', '#ccb7de'
      ]
    },
    
    // 创建旭日图配置
    createSunburstOptions(data) {
      return {
        tooltip: {
          trigger: 'item'
        },
        color: this.getColorTheme(),
        series: [
          {
            type: 'sunburst',
            data: [data],
            radius: ['15%', '90%'],
            label: {
              rotate: 'radial',
              minAngle: 10
            },
            emphasis: {
              focus: 'ancestor'
            },
            itemStyle: {
              borderWidth: 1,
              borderColor: 'rgba(255,255,255,0.3)'
            },
            levels: [
              {},
              {
                r0: '15%',
                r: '40%',
                itemStyle: {
                  borderWidth: 2
                },
                label: {
                  rotate: 'tangential'
                }
              },
              {
                r0: '40%',
                r: '65%',
                label: {
                  align: 'right'
                }
              },
              {
                r0: '65%',
                r: '90%',
                label: {
                  position: 'outside',
                  padding: 3,
                  silent: false
                },
                itemStyle: {
                  borderWidth: 3
                }
              }
            ]
          }
        ]
      }
    },
    
    // 处理图表点击事件
    async handleChartClick(params) {
      // 检查是否点击了图表中心（当前层级的节点）
      if (params.name === this.navigationPath[this.navigationPath.length - 1].name) {
        // 如果已经是最顶层，则不做处理
        if (this.navigationPath.length <= 1) {
          return
        }
        
        // 返回上一级
        const previousIndex = this.navigationPath.length - 2
        await this.backToLevel(previousIndex)
        return
      }
      
      // 确保点击的是部门节点（不是状态节点）
      if (!params.data || params.data.deptId === undefined || params.data.deptType === undefined) {
        return
      }
      
      const clickedDept = params.data
      
      // 根据点击的部门类型进行处理
      switch (clickedDept.deptType) {
        case 0: // 总部
          // 如果点击总部，回到顶级视图
          this.navigateToLevel(0)
          break
          
        case 1: // 烟站
          // 导航到烟站
          this.navigateToLevel(1, clickedDept.deptId, clickedDept.name)
          break
          
        case 2: // 乡镇
          // 导航到乡镇
          this.navigateToLevel(2, clickedDept.deptId, clickedDept.name)
          break
          
        case 3: // 乡村组（最底层，无需操作）
          this.$message.info('已经是最底层级，无法继续下钻')
          break
      }
    },
    
    // 导航到指定层级
    async navigateToLevel(level, deptId = null, deptName = null) {
      // 更新导航路径
      if (level === 0) {
        // 如果是总部级别，重置导航路径
        this.navigationPath = [{ id: null, name: '总部', level: 0 }]
      } else {
        // 检查是否已经在导航路径中
        const existingIndex = this.navigationPath.findIndex(item => item.id === deptId)
        
        if (existingIndex !== -1) {
          // 如果已存在，截取到该位置
          this.navigationPath = this.navigationPath.slice(0, existingIndex + 1)
        } else {
          // 如果不存在，添加到路径
          this.navigationPath.push({ id: deptId, name: deptName, level })
        }
      }
      
      // 更新视图数据
      await this.updateViewForLevel(level, deptId)
    },
    
    // 根据索引回到指定层级
    async backToLevel(index) {
      if (index >= this.navigationPath.length - 1) {
        return
      }
      
      // 获取要导航到的层级
      const targetLevel = this.navigationPath[index]
      
      // 更新导航路径
      this.navigationPath = this.navigationPath.slice(0, index + 1)
      
      // 更新视图数据
      await this.updateViewForLevel(targetLevel.level, targetLevel.id)
    },
    
    // 重置到顶级层级
    async resetCurrentLevel() {
      await this.navigateToLevel(0)
    },
    
    // 日期变化处理
    handleDateChange(dates) {
      if (dates) {
        this.dateRange = dates
      } else {
        this.dateRange = [
          moment().startOf('year').format('YYYY-MM-DD'),
          moment().format('YYYY-MM-DD')
        ]
      }
    },
    
    // 重新加载数据（如日期变更时）
    async loadData() {
      // 重置状态
      this.navigationPath = [{ id: null, name: '总部', level: 0 }]
      this.currentLevel = 0
      this.currentDeptId = null
      
      // 清空现有数据
      this.treeData = {
        headOffice: null,
        stations: [],
        townships: {},
        villageGroups: {}
      }
      
      // 重新初始化
      await this.initializeData()
    }
  }
}
</script>

<style lang="scss" scoped>
.statistics-container {
  padding: 20px;
  background: #f5f7fa;
  height: calc(100vh - 120px);
  
  .search-container {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    padding: 15px;
    background: #fff;
    border-radius: 4px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    flex-wrap: wrap;
    gap: 10px;
    
    .date-range {
      display: flex;
      align-items: center;
      
      .el-button {
        margin-left: 10px;
      }
    }
    
    .status-legend {
      display: flex;
      align-items: center;
      
      .legend-items {
        display: flex;
        flex-wrap: nowrap;
        
        .legend-item {
          display: flex;
          align-items: center;
          margin-right: 10px;
          
          .color-box {
            width: 14px;
            height: 14px;
            border-radius: 2px;
            margin-right: 4px;
          }
          
          span {
            font-size: 13px;
            white-space: nowrap;
          }
        }
      }
    }
    
    .level-indicator {
      display: flex;
      align-items: center;
      
      span {
        margin-right: 5px;
        font-weight: bold;
        white-space: nowrap;
      }
      
      .clickable {
        cursor: pointer;
        color: #409EFF;
        
        &:hover {
          text-decoration: underline;
        }
      }
    }
  }
  
  .charts-container {
    display: flex;
    height: calc(100% - 60px);
    
    .chart-wrapper {
      width: 50%;
      height: 100%;
      
      &:first-child {
        margin-right: 20px;
      }
    }
  }
}
</style> 